# -*- coding: utf-8 -*-
#
# @Time    ： 2024/4/23  16:40
# @Auther  ： 徐良
# File     :  testPanel.py
from PySide6.QtSql import QSqlDatabase, QSqlQuery
from PySide6.QtWidgets import QWidget
from baseApp.ui.testUI import Ui_Form
from PySide6.QtWidgets import QDataWidgetMapper
import os

from PySide6.QtCore import Qt, QModelIndex, QAbstractTableModel

class MyTableModel(QAbstractTableModel):
    def __init__(self, data, headers):
        super().__init__()
        self._data = data
        self._headers = headers

    def rowCount(self, parent=QModelIndex()):
        return len(self._data)

    def columnCount(self, parent=QModelIndex()):
        return len(self._data[0]) if self._data else 0

    def data(self, index, role=Qt.DisplayRole):
        if not index.isValid() or not (0 <= index.row() < len(self._data)):
            return None
        row = index.row()
        col = index.column()
        if role == Qt.DisplayRole or role == Qt.EditRole:
            return self._data[row][col]
        return None

    def setData(self, index, value, role=Qt.EditRole):
        if not index.isValid() or not (0 <= index.row() < len(self._data)):
            return False
        row = index.row()
        col = index.column()
        if role == Qt.EditRole:
            self._data[row][col] = value
            self.dataChanged.emit(index, index, [role])
            return True
        return False

    def flags(self, index):
        if not index.isValid():
            return Qt.NoItemFlags
        return Qt.ItemIsEditable | Qt.ItemIsEnabled | Qt.ItemIsSelectable

    def headerData(self, section, orientation, role=Qt.DisplayRole):
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            return self._headers[section] if 0 <= section < len(self._headers) else None
        return None

    def loadDataFromTable(self, table_name):
        # 创建数据库连接
        self.db = QSqlDatabase.addDatabase('QSQLITE')
        # 设置数据库文件名
        self.db.setDatabaseName('../data/autoTask.db')
        # 打开数据库
        if not self.db.open():
            print("Error: Unable to open database")
            return

        # 执行查询获取表中的数据
        query = QSqlQuery()
        if not query.exec(f"SELECT * FROM {table_name}"):
            print("Error:", query.lastError().text())
            return False

        # 将查询结果转换为二维列表
        self._data = []
        self._headers = []
        while query.next():
            row_data = [query.value(i) for i in range(query.record().count())]
            self._data.append(row_data)

        self._headers = [query.record().fieldName(i) for i in range(query.record().count())]
        print(self._data)
        return True




class TestPanel(QWidget, Ui_Form):
    """
    pass
    """
    def __init__(self, parent=None):
        super(TestPanel, self).__init__()
        self.setupUi(self)
        self.readD()

    def readD(self):

        self.Model = MyTableModel([], [])
        self.Model.loadDataFromTable('t_pnpManage')
        print(self.Model.rowCount())
        self.tableView.setModel(self.Model)
        index = self.Model.index(0, 3)
        dd = self.Model.data(index)
        print(dd)

        # 创建映射关系
        self.mapper = QDataWidgetMapper()
        self.mapper.setModel(self.Model)

        self.mapper.addMapping(self.lineEdit1, 0)
        self.mapper.addMapping(self.lineEdit2, 1)
        self.mapper.addMapping(self.lineEdit3, 2)
        self.mapper.addMapping(self.lineEdit4, 3)

        # 设置当前索引
        self.mapper.setCurrentIndex(0)

        # 连接控件的textChanged信号到提交方法
        self.lineEdit1.textChanged.connect(self.submitData)
        self.lineEdit2.textChanged.connect(self.submitData)
        self.lineEdit3.textChanged.connect(self.submitData)
        self.lineEdit4.textChanged.connect(self.submitData)


    def submitData(self):
        """
        提交控件数据到模型
        """
        self.mapper.submit()




if __name__ == '__main__':
    import sys
    from PySide6.QtWidgets import QApplication, QDataWidgetMapper, QWidget

    app = QApplication(sys.argv)
    window = TestPanel()
    window.show()
    sys.exit(app.exec())


